package com.caifeng.redis.util.captcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.lang.UUID;
import com.caifeng.domain.ResponseCode;
import com.caifeng.domain.ServiceException;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Component
@Aspect
public class CaptchaMaker {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Around("@annotation(com.caifeng.redis.util.captcha.MiaoCaptcha)")
    public Object makeCaptcha(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
        String captchaKey = request.getHeader("captchaKey");
        String captchaValue = request.getHeader("captchaValue");
        if (
                StringUtils.isBlank(captchaKey) || StringUtils.isBlank(captchaValue)
                || !captchaValue.equalsIgnoreCase(redisTemplate.opsForValue().getAndDelete(captchaKey))
        ) {
            ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(150, 40, 5, 4);

            try {
                if (response != null) {
                    shearCaptcha.write(response.getOutputStream());
                }
            } catch (IOException e) {
                throw new ServiceException("验证码生成失败");
            }

            //获取验证码中的文字内容

            captchaKey = String.valueOf(UUID.fastUUID());
            redisTemplate.opsForValue().set(captchaKey, shearCaptcha.getCode(), 60, TimeUnit.SECONDS);
            throw new ServiceException(ResponseCode.CAPTCHA_ERROR, captchaKey);
        }
        return pjp.proceed();
    }
}
